/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-07-26     yuanzihao    init
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <fal.h>
#include <flashdb.h>

extern struct fdb_kvdb kvdb;
struct fdb_blob blob;

static int read_cfg(void *buff, int len)
{
    size_t saved_len;

    fdb_kv_get_blob(&kvdb, "wlan_cfg_info", fdb_blob_make(&blob, buff, len));
    if (saved_len == 0)
    {
        return 0;
    }
    return len;
}

static int get_len(void)
{
    int len;
    size_t saved_len;

    fdb_kv_get_blob(&kvdb, "wlan_cfg_len", fdb_blob_make(&blob, &len, sizeof(len)));
    saved_len = len;
    if (saved_len == 0)
    {
        return 0;
    }

    return len;
}

static int write_cfg(void *buff, int len)
{
    /* set and store the wlan config lengths to Env */
    fdb_kv_set_blob(&kvdb, "wlan_cfg_len", fdb_blob_make(&blob, &len, sizeof(len)));

    /* set and store the wlan config information to Env */
    fdb_kv_set_blob(&kvdb, "wlan_cfg_info", fdb_blob_make(&blob, buff, len));

    return len;
}

static const struct rt_wlan_cfg_ops ops =
    {
        read_cfg,
        get_len,
        write_cfg};

void wlan_autoconnect_init(void)
{
    fal_init();

    rt_wlan_cfg_set_ops(&ops);
    rt_wlan_cfg_cache_refresh();
}
